/*
 * @LastEditTime: 2023-02-28 11:30:54
 */
import Axios from "axios";
import { NewAlbum } from "../Models/NewAlbum.schema";
import { createNewAlbumDataDTO } from "../DTO/NewAlbum.dto";

export class NewAlbumController {
  constructor(private readonly newAlbumModel: typeof NewAlbum) { }

  /**
 * 创建专辑
 * @param dto 数据传输对象
 * @returns 返回创建对象
 */

  async createNewAlbumItem(dto: createNewAlbumDataDTO) {
    try {
      return {
        code: 200,
        message: "创建成功",
        data: await NewAlbum.create(dto),
      };
    } catch (error) {
      return await error;
    }
  }



  //查询全部数据
  async findAll() {
    try {
      if (await this.newAlbumModel.find().count() != 0)
        return {
          code: 200,
          message: "查询成功",
          data: await this.newAlbumModel.find(),

        };
      else
        return {
          code: 400,
          message: "该数据集不存在数据"
        }
    }
    catch (error) {
      return await error;
    }
  }

  // 获取新碟信息
  async getNew() {
    if (await this.newAlbumModel.find().count() == 0) {
      try {
        const data = await Axios.get(`http://162.14.104.16:3005/top/album?area=ALL`)
        const res = data.data as {
          code: string,
          weekData: {
            artist: {
              name: string,
              id: string
            },
            picUrl: string,
            name: string,
            id: string
          }[],
          hasMore: boolean,
        }
        for (let i = 0; i < res.weekData.length; i++) {
          let tempData = {
            id: res.weekData[i].id,
            name: res.weekData[i].name,
            cover: res.weekData[i].picUrl,
            auther: {
              id: res.weekData[i].artist.id,
              name: res.weekData[i].artist.name
            } as createNewAlbumDataDTO
          }
          console.log(tempData)
          await this.createNewAlbumItem(tempData);
        }
        return {
          code: 200,
          message: '查询成功2',
          data: await this.newAlbumModel.find(),
        }
      } catch (error) {
        return error;
      }
    }
    else
      return {
        code: 200,
        message: '查询成功1',
        data: await this.newAlbumModel.find(),
      }
  }
}